package cn.csc.module.order.mq.consumer;

import cn.csc.module.order.dal.dataobject.item.OrderItemDO;
import cn.csc.module.order.dal.dataobject.order.OrderDO;
import cn.csc.module.order.dal.mysql.order.OrderMapper;
import cn.csc.module.order.mq.producer.OrderSubmitProducer;
import cn.csc.module.order.mq.producer.hzh.OrderSubmitForHzhProducer;
import cn.csc.module.order.service.item.OrderItemService;
import cn.csc.module.order.service.order.OrderService;
import cn.csc.module.pay.message.PayOrderNotifyMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;
import java.util.function.Consumer;

import static cn.csc.framework.common.util.json.JsonUtils.toJsonString;
import static cn.csc.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;

/**
 * 消费支付订单支付成功消息
 * topic: pay_order_notify
 * Bean的注解名 payOrderNotify 与channel的前半段相同(payOrderNotify-in-0)
 * rocketmq消息发送重试：https://rocketmq.apache.org/zh/docs/featureBehavior/05sendretrypolicy
 * {@link PayOrderNotifyMessage}
 * @author liuchuang
 * @version 1.0
 * @date 2024/1/29 16:45
 * @modify
 */
@Slf4j
@Configuration
public class PayOrderNotifyConsumer{

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private OrderSubmitProducer orderSubmitProducer;

    @Autowired
    private OrderSubmitForHzhProducer orderSubmitForHzhProducer;

    /**
     * 订单支付成功，更新商品订单支付状态， 通知库存扣减
     * message 支付订单支付成功通知消息
     */
    @Bean
    public Consumer<PayOrderNotifyMessage> payOrderNotify(){
        return message -> {
            log.info("payOrderNotifyConsumer支付回调开始: {}", toJsonString(message));
            try {
                // 更新商品订单的支付状态(order_status=2)
                orderService.updateByToPaySuccess(message.getMerchantOrderId());
                OrderDO orderDO = orderMapper.selectByMerchantOrderId(message.getMerchantOrderId());
                List<OrderItemDO> orderItemDOS = orderItemService.getItemByOrderId(orderDO.getId());
                orderSubmitProducer.sendOrderSubmitMessage(orderItemDOS);
                // 发送mq消息给park-pc-backend
                orderSubmitForHzhProducer.sendOrderSubmitMessage(orderDO, getLoginUserId());
                // 使用事务消息 https://blog.csdn.net/gsls200808/article/details/133278138
                // 发送事务消息，订单支付成功 通知库存扣减
                // 同步发送，失败重试3次
            } catch (Exception e) {
                log.error("订单支付成功,消息消费失败:{}", message, e);
            }
        };
    }

}
